package net.wanglu.www.zzz.utils;

import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;

import net.didion.jwnl.JWNL;
import net.didion.jwnl.JWNLException;
import net.didion.jwnl.data.IndexWord;
import net.didion.jwnl.data.POS;
import net.didion.jwnl.data.PointerUtils;
import net.didion.jwnl.data.Synset;
import net.didion.jwnl.data.Word;
import net.didion.jwnl.data.list.PointerTargetNode;
import net.didion.jwnl.data.list.PointerTargetNodeList;
import net.didion.jwnl.dictionary.Dictionary;
import edu.stanford.nlp.process.Morphology;

public class JwnlUtils {

	static boolean init = false;
	public static void initJWNL() throws Exception {
		if ( init) return;
		try {
			InputStream is = JwnlUtils.class.getResourceAsStream("file_properties.xml");
			JWNL.initialize(is);
			init = true;
		} catch (JWNLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	static PointerUtils pu = PointerUtils.getInstance();;
	public static Collection<?> findSynonyms(String word, String tag) throws Exception {
		String lemma = Morphology.lemmaStatic(word, tag, true);
		IndexWord indexWord = null;
		if ( tag.startsWith("NN")) {
			indexWord = Dictionary.getInstance().getIndexWord(POS.NOUN, lemma);
		} else if ( tag.startsWith("JJ")) {
			indexWord = Dictionary.getInstance().getIndexWord(POS.ADJECTIVE, lemma);
		} else if ( tag.startsWith("RB")) {
			indexWord = Dictionary.getInstance().getIndexWord(POS.ADVERB, lemma);
		} else if ( tag.startsWith("VB")) {
			indexWord = Dictionary.getInstance().getIndexWord(POS.VERB, lemma);
		}
		
		if ( indexWord == null) return null;
		HashSet<String> options = new HashSet<String>(64);
		Synset[] set = indexWord.getSenses();
		for( int i=0; i<set.length; i++) {
			Synset ss = set[i];
			PointerTargetNodeList list = pu.getSynonyms(ss);
			for( int j=0 ;j<list.size(); j++) {
				PointerTargetNode pt = (PointerTargetNode) list.get(j);
				Synset s = pt.getSynset();
				Word[] words = s.getWords();
				for( int k=0; k<words.length; k++) {
					String option = words[k].getLemma();
					if ( option.contains("(") || option.contains("_")) continue;
					options.add(option);
				}
			}
			Word[] words = set[i].getWords();
			if ( words == null || words.length <1) continue;
			for( int j=0; j<words.length; j++) {
				String option = words[j].getLemma();
				if ( option.contains("(") || option.contains("_")) continue;
				options.add(option);
			}
		}
		
		if ( options.size() ==0) return null;
		return options;
	}
}
